const moment = require('moment');
const fs = require('fs');
const path = require('path');
const request = require('request');
const rename = think.promisify(fs.rename, fs);

module.exports = class extends think.Service {
    async path() {
        const files = this.data;
        let Path = [];
        for (let key in files) {
            if (files[key].size > 0) {
                let extName = '';  //后缀名
                switch (files[key].type) {
                    case 'image/pjpeg':
                        extName = 'jpg';
                        break;
                    case 'image/jpeg':
                        extName = 'jpg';
                        break;
                    case 'image/png':
                        extName = 'png';
                        break;
                    case 'image/x-png':
                        extName = 'png';
                        break;
                }

                if (extName.length === 0) {
                    return;
                }
                let avatarName = 'IMG' + moment().format('X') + Math.random().toString().substr(2, 7) + '.' + extName;
                const filepath = path.join(think.ROOT_PATH, 'www/static/image/' + avatarName);
                think.mkdir(path.dirname(filepath));
                await rename(files[key].path, filepath);
                // Path.push({url: "http://www.xiaojukaola.com:8360/static/image/" + avatarName, id: key.split('_')[0]});
                Path.push({url: think.config('xcx.domain')+'static/image/' + avatarName, id: key.split('_')[0]});
            }
        }
        return Path;
    }

    upload(img_src) {
        return new Promise(resolve => {
            request.head(img_src, function(err, res, body) {
                if (err) {
                    console.log(err);
                }
            });
            let imgName = +(new Date()) + '' + Math.ceil(Math.random() * 89 + 10);
            request(img_src).pipe(fs.createWriteStream('D:/static/head/' + imgName + '.png'));
            resolve(think.config('xcx.upload_domain') + 'head/' + imgName + '.png');
        });
    }
};
